package top.blackr.folivora.common.security;

import cn.dev33.satoken.stp.StpInterface;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;
import top.blackr.folivora.common.security.crud.model.entity.SysMenu;
import top.blackr.folivora.common.security.crud.model.entity.SysRole;
import top.blackr.folivora.common.security.crud.model.entity.SysRoleMenu;
import top.blackr.folivora.common.security.crud.model.entity.SysUserRole;
import top.blackr.folivora.common.security.crud.repository.SysMenuRepository;
import top.blackr.folivora.common.security.crud.repository.SysRoleMenuRepository;
import top.blackr.folivora.common.security.crud.repository.SysRoleRepository;
import top.blackr.folivora.common.security.crud.repository.SysUserRoleRepository;

import java.util.Collections;
import java.util.List;

/**
 * 自定义权限验证接口扩展
 */
@Component
@AllArgsConstructor
public class StpInterfaceImpl implements StpInterface {

    private final SysUserRoleRepository userRoleService;
    private final SysRoleMenuRepository roleMenuService;
    private final SysMenuRepository menuService;
    private final SysRoleRepository roleService;

    /**
     * 返回一个账号所拥有的权限码集合
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        // 查询当前用户所有的角色信息
        List<SysUserRole> userRoles = userRoleService.list(Wrappers.<SysUserRole>lambdaQuery()
                .eq(SysUserRole::getUserId, loginId));
        if (userRoles.isEmpty()) {
            return Collections.emptyList();
        }
        // 查询角色关联的权限容器（菜单、按钮等）
        List<SysRoleMenu> roleMenus = roleMenuService.list(Wrappers.<SysRoleMenu>lambdaQuery()
                .in(SysRoleMenu::getRoleId, userRoles.stream().map(SysUserRole::getRoleId).toList()));
        if (roleMenus.isEmpty()) {
            return Collections.emptyList();
        }
        // 查询具体的权限
        List<SysMenu> menus = menuService.list(Wrappers.<SysMenu>lambdaQuery()
                .in(SysMenu::getMenuId, roleMenus.stream().map(SysRoleMenu::getMenuId).toList()));
        return menus.stream().map(SysMenu::getPermission).toList();
    }

    /**
     * 返回一个账号所拥有的角色标识集合 (权限与角色可分开校验)
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        // 查询当前用户所有的角色信息
        List<SysUserRole> userRoles = userRoleService.list(Wrappers.<SysUserRole>lambdaQuery()
                .eq(SysUserRole::getUserId, loginId));
        if (userRoles.isEmpty()) {
            return Collections.emptyList();
        }
        // 查询具体的角色
        List<SysRole> menus = roleService.list(Wrappers.<SysRole>lambdaQuery()
                .in(SysRole::getRoleId, userRoles.stream().map(SysUserRole::getRoleId).toList()));
        return menus.stream().map(SysRole::getRoleCode).toList();
    }

}
